<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    modal
    append-to-body
    class="pms-zr-dialog pms-zr-next"
    v-bind="$attrs"
    width="50%"
    v-on="$listeners"
  >
    <div class="container">
      <div class="select">
        <div class="box">
          <div class="title">下一步节点</div>
<!--            <div class="content" v-if="status">-->
<!--                <div class="user-select-item" style="text-align: left;color: #eb4b4b;text-indent: 1em;background-color: #ffefe5">{{ loginName}}</div>-->
<!--            </div>-->
          <div class="content">
            <div v-for="(item,index) in nodeList" :key="index" class="node-item" :class="{'clicked' : item.clicked}" @click="nodeClick(item)">
              {{ item.nodeName }}
            </div>
          </div>
        </div>
        <div class="box">
          <div class="title">已选办理人</div>
          <div class="content">
            <div v-if="userSelectedName" class="user-select-item">
              <span class="el-icon-user" style="margin-right: 6px;" />
              <span>{{ userSelectedName }}&nbsp;&nbsp;{{ selectedUserId ? `(${selectedUserId})` : '' }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="message">
        <el-form ref="nextPageForm" class="pms-details" :model="form" :rules="rules" label-width="100">
          <el-form-item label="办理意见" prop="opinion">
            <div style="display: flex; margin-right: 10px;">
              <el-button type="text" class="btnColor" @click="doOpenCommonOpinion">
                （自定义常用意见）
              </el-button>
              <el-select v-model="opinion" :popper-append-to-body="false" placeholder="请选择" class="pms-select" size="mini" style="margin-left: 10px" @change="handleSelectChange">
                <el-option
                  v-for="item in opinions"
                  :key="item.id"
                  :value="item.opinion"
                />
              </el-select>
            </div>
          </el-form-item>
          <el-input v-model="form.opinion" style="margin-top: 20px;" class="pms-textarea" type="textarea" placeholder="请输入办理意见" :rows="4" maxlength="500"/>
        </el-form>
      </div>
    </div>
    <div slot="footer">
      <el-button class="pms-button-primary" @click="confirm">确 定</el-button>
      <el-button class="pms-button-primary" @click="cancel">取 消</el-button>
    </div>

    <!--常用意见列表-->
    <common-opinion v-if="ifCommonOpinion" :visible.sync="ifCommonOpinion" @close="ifCommonOpinion = false" />
  </el-dialog>

</template>

<script>
import { getNextActivities, getNextUsersByRole, getCommonOpinion,getNextUsersByRoleAcceptance } from '@/api/workFlow'
import CommonOpinion from '@/components/nextPerson/commonOpinionList'
import { msgInfoEl } from '@/utils'

export default {
  name: 'NextPage',
  components: { CommonOpinion },
  props: {
    title: {
      type: String,
      default: '流程提交'
    },
    // 流程实例ID
    processInstId: {
        type: [String, Number],
        default: ''
    },
    // 活动实例ID
    activityInstId: {
        type: [String, Number],
        default: ''
    },
    // 活动定义ID
    activityDefId: {
        type: [String, Number],
        default: ''
    },
    // 流程实例名称
    processDefName: {
      type: String,
      default: ''
    },
    // 办理意见是否必填
    opinionValid: {
      type: Boolean,
      default: true
    },
    orgId: {
      type: String,
      default: ''
    },
    orgIds: {
      type: String,
      default: ''
    },
    orgCode: {
      type: String,
      default: ''
    },
    userIds: {
      type: String,
      default: ''
    },
    // 流程下一步路由
    route: {
      type: String,
      default: ''
    },
    // 是否展示下一步节点或办理人
    status: {
        type: Boolean,
        default: false
    },
    prjId:{
       type: String,
        default: ''
    },
    prjDetail: {
      type: Object,
      default: () => ({ })
    },
  },
  data() {
    return {
      detailId: '',
      nTemplateId: '',
      nodeList: [], // 下一步办理节点
      userSelected: {}, // 已选择的人员节点
      toSelectdata: [], // 可选办理人树型
      actDefIdSelected: '', // 已选择的节点id
      form: {
        opinion: '' // 办理意见
      },
      rules: {
        opinion: [
          { required: true, message: '请输入办理意见', trigger: 'change' }
          // { min: 10, message: '至少输入10个字', trigger: 'blur' }
        ]
      },
      finishNode: false,
      selectedUserId: '', // 已选办理人账号
      selectedNodeName: '', // 已选项目节点名称
      opinion: '',
      finish: false,
      opinions: [],
      roleName: '',
      ifCommonOpinion: false, // 常用意见页面
      nextSceneId: '', // 场景id
      titles:"加载中...",
      loginName:'',
    }
  },
  computed: {
    userSelectedName() {
      return this.userSelected.empName
    }
  },
  watch: {
    opinionValid: {
      handler: function(newVal) {
        if (!newVal) {
          this.rules = {}
        }
      },
      immediate: true
    }
  },
  mounted() {
    // if (this.status) {
    //     //下一步节点值事根据role自己写死
    //     if(+this.prjDetail.role === 1){
    //         this.loginName = '项目管理岗审核'
    //         this.userSelected={
    //             empName:this.prjDetail?.newPrjManagerName,
    //             empId:this.prjDetail?.newPrjManagerAccount
    //         }
    //         this.selectedUserId = this.prjDetail?.newPrjManagerAccount || ''
    //     }else{
    //         this.loginName = '原项目管理岗审核'
    //         this.userSelected={
    //             empName:this.prjDetail?.oldPrjManagerName,
    //             empId:this.prjDetail?.oldPrjManagerAccount
    //         }
    //         this.selectedUserId = this.prjDetail?.oldPrjManagerAccount || ''
    //     }
    // }else{
    //     this.doSearchNextActivity()
    // }
    this.doSearchNextActivity()
    this.getCommonOpinions()
  },
  methods: {
    doSearchNextActivity() {
      getNextActivities({
        processInstId: this.processInstId,
        actInsetId: this.activityInstId,
        route: this.activityDefId === 'adjust_prj1' ? this.route :''
      }).then(res => {
        if (+res.code !== 200) {
          return Promise.reject(res)
        }
        const { data } = res
        this.nodeList = data
        if (data.length > 0) {
            // 默认选中第一个节点
            this.nodeClick(data[0])
        }
      })
    },
    // 获取节点可选办理人 跨项目调整不需要，直接默认人
    doSearchNextUsersByRole(item) {
      const param = {
          'procInstId': this.processInstId,
          'nodeId': item.nodeId,
          'userIds': this.userIds,
          'orgCode': this.orgCode,
          'orgId': this.orgId,
          'detailId': item.detailId,
          'templateId': item.templateId
      }
      this.finish = item.procEnd
      getNextUsersByRole(param).then(res => {
          if (+res.code !== 200) {
            return Promise.reject(res)
          }
          this.toSelectdata = res.data
      })
    },
    // 选择节点
    nodeClick(item) {
      this.nodeList.forEach(i => {
        i.clicked = false
      })
      item.clicked = true
      this.finishNode = item.finishNode
      this.actDefIdSelected = item.nodeId
      this.selectedNodeName = item.nodeName
      this.roleName = item.roleName
      this.nextSceneId = item.sceneId
      this.procEnd = item.procEnd
      this.detailId = item.detailId
      this.nTemplateId = item.templateId
      this.finish = item.procEnd
      // procEnd表示当前阶段流程结束，finishNode表示当前节点是否为结束节点；例：跨阶段时，procEnd为true，finishNode为false
      if (!item.finishNode) {
          // this.doSearchNextUsersByRole(item)
          //原项目管理岗审核
          if( item.nodeId === 'adjust_prj3'){
              this.userSelected={
                  empName:this.prjDetail?.oldPrjManagerName,
                  empId:this.prjDetail?.oldPrjManagerAccount
              }
              this.selectedUserId = this.prjDetail?.oldPrjManagerAccount || ''
          }else{
              this.userSelected={
                  empName:this.prjDetail?.newPrjManagerName,
                  empId:this.prjDetail?.newPrjManagerAccount
              }
              this.selectedUserId = this.prjDetail?.newPrjManagerAccount || ''
          }
      } else {
           console.log('流程结束，没有可选办理人')
           this.titles = ''
      }
    },
    // 提交后返回值
    doEmit() {
      this.$emit('selected', this.userSelected)
      this.$emit('doNextEntity', {
        processInstId: this.processInstId,
        processDefId: this.processDefId,
        actDefId: this.activityDefId,
        templateId: this.processDefName, // 模板id
        nodeId: this.actDefIdSelected, // 节点id
        route: this.route, // 路由
        opinion: this.form.opinion, // 审批意见
        finishNode: this.finishNode, // 当前已选择节点是否为结束节点
        finish: this.finish,
        procEnd: this.procEnd, // 当前阶段流程是否结束
        nextSceneId: this.nextSceneId, // 场景id
        detailId: this.detailId,
        nTemplateId: this.nTemplateId,
        ...this.userSelected
      })
      this.$emit('update:visible', false)
    },
    // 确认
    confirm() {
        if ( !this.finishNode && !Object.keys(this.userSelected).length) {
            msgInfoEl({
                type: 'error',
                message: '请选择下一节点办理人'
            })
            return
        }
      this.opinionValid && this.$refs['nextPageForm'].validate((valid) => {
        // 校验通过
        valid && this.doEmit()
      })
      if (!this.opinionValid) {
        this.doEmit()
      }
    },
    // 取消
    cancel() {
      this.$refs['nextPageForm'].resetFields()
      this.$emit('selected', {})
      this.$emit('update:visible', false)
    },
    handleSelectChange(value) {
        this.$set(this.form, 'opinion', value)
    },
    // 获取常用意见
    getCommonOpinions() {
        getCommonOpinion().then(res => {
            if (+res.code !== 200) {
              return Promise.reject(res)
            }
            this.opinions = res.data
        })
    },
    // 打开常用意见页面
    doOpenCommonOpinion() {
        this.ifCommonOpinion = true
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
